/** @Author: FengKongLi 
 * @Date: 2021-08-16 19:06:28 
 * @Last Modified by: FengKongLi
 * @Last Modified time: 2021-08-22 16:36:28
*/
// 栏目管理页面
<template>
  <div class="category-list">
    <!-- 添加按钮 -->
    <div class="btn">
      <el-button @click="toAdd" type="primary">添加</el-button>
    </div>
    <!-- 表格数据展示 -->
    <div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="id" label="栏目编号"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="icon" label="图标">
          <template slot-scope="scope">
            <el-image
              style="width: 50px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="排序号"> </el-table-column>

        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button @click="toEdit(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="toDelete(scope.row.id)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page-div">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加、编辑弹出的对话框 -->
    <div>
      <el-dialog :title="title" :visible.sync="visible" @close="resetForm">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item
            prop="name"
            label="栏目名称"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item prop="num" label="序号" :label-width="formLabelWidth">
            <el-input v-model="form.num"></el-input>
          </el-form-item>
          <el-form-item prop="icon" label="图标" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageQuery, deleteById, saveOrUpdate } from "@/api/productCategory";
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      // 上传图标地址
      showFileURL,
      uploadFileURL,
      // 表格展示的数据
      tableData: [],
      params: {
        page: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      // 对话框数据
      form: {},
      // 默认隐藏对话框
      visible: false,
      // 对话框标题
      title: "添加栏目信息",
      //表单控件标题的宽度
      formLabelWidth: "80px",
      // 上传图片的路径
      imageUrl: "",
      // 校验规则
      rules: {
        name: [{ required: true, message: "请输入栏目名称", trigger: "blur" }],
        icon: [{ required: true, message: "请选择图标", trigger: "change" }],
      },
    };
  },
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.queryCategoryData();
      },
      deep: true,
    },
  },
  created() {
    this.queryCategoryData();
  },
  
  methods: {
    // 获取栏目分类数据
    async queryCategoryData() {
      const res = await pageQuery(this.params);
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    // 条/页 发生变化时
    handleSizeChange(val) {
      this.params = {
        page: 1,
        pageSize: val,
      };
    },
    // 页数发生变化时
    handleCurrentChange(val) {
      this.params.page = val;
    },
    // 添加按钮事件
    toAdd() {
      this.title = "添加栏目信息";
      this.form = {};
      this.imageUrl = "";
      this.visible = true;
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    // 图片上传成功后的回调函数
    handleAvatarSuccess(res,file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.icon = file.response;
    },
    // 上传成功之前的回调函数
    beforeAvatarUpload(file) {
      // 判断图片的格式和大小
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 确定按钮点击事件
    toSave() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await saveOrUpdate(this.form);
          if (res.status === 200) {
            this.$notify({
              title: "保存成功",
              message: res.message,
              type: "success",
            });
            // 重新请求，到达刷新效果
            this.queryCategoryData();
            // 调用重置表单方法
            this.resetForm();
            // 对话框关闭
            this.visible = false;
          } else {
            return false;
          }
        }
      });
    },
    // 编辑按钮点击事件
    toEdit(row) {
      // this.querycategoryData();
      this.title = "编辑栏目信息";
      this.form = { ...row };
      this.imageUrl = row.icon;
      this.visible = true;
      
    },
    // 删除按钮
    async toDelete(id) {     
      this.$confirm("此操作将永久删除这条数据,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(async () => {
          let res = await deleteById({id});
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
          }
          this.queryCategoryData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
      });
    }
  },
};
</script>

<style scoped>
 .btn{
   margin-bottom: 10px;
 }
</style>
